package impl

import (
	"log"
	"time"
	"ylb/config"
	"ylb/entity"
	"ylb/tool"
)

type EmailServiceImpl struct{}

func (esi EmailServiceImpl) Send(email entity.Email, connection entity.EmailConnection) error {
	config := map[string]string{
		"user": connection.User,
		"pass": connection.Pass,
		"host": connection.Host,
	}
	return tool.SendMail(email.Subject, email.Body, email.Receiver, config)

}
func (esi EmailServiceImpl) SendHtml(email entity.Email) error {

	email.Body = "<html><head> <meta charset=\"utf-8\"><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></head><body>" + email.Body + "</body></html>"
	return esi.SendDefault(email)
}

func (esi EmailServiceImpl) SendDefault(email entity.Email) error {

	connection, err := config.GetEmailConnectionConfig()

	if err != nil {
		connection = entity.EmailConnection{
			User: "3625919740@qq.com",
			Pass: "pikjjvosbtikcifj",
			Host: "smtp.qq.com",
		}
		log.Println("[启动邮箱默认配置]...")
	}
	log.Printf("[邮箱服务配置]: %v\n", connection)

	return esi.Send(email, connection)
}

func (esi EmailServiceImpl) SendCode(subject string, head string, receiver string) (string, error) {
	code := tool.GetRandomCode(6)
	email := entity.Email{
		Subject: subject,
		Body: `
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
	 <style>

        .code-box{
            width: 100%;
            min-width: 100vw;
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: start;
        }
      
    </style>
</head>

<body style="font-family: Helvetica">
  <div>
        <h3>` + head + `</h3>
        <div class="code-box" style="background-color:#171D20 ">
            <div style="
            background-color: #e3e3e3;
            color: teal;
            font-size: 35px;
            padding: 1vh 4vw 1vh 4vw;
            margin-top: 10vh;">
                ` + code + `
            </div>
        </div>
    </div>
</body>

</html>
`,
		Receiver: []string{
			receiver,
		},
	}
	err := esi.SendDefault(email)

	return code, err
}
func (esi EmailServiceImpl) SendManyCode(subject string, head string, receiver []string) (map[string]string, error) {

	return nil, nil
}

func (esi EmailServiceImpl) SendCodeAndSetRedis(subject string, head string, receiver string, key string) error {
	//发送邮件code
	code, err := esi.SendCode(subject, head, receiver)
	//存入redis
	connection := tool.GetRedisConnection()
	connection.Set(key, code, time.Second*60)
	connection.Close()
	return err
}
